package gsw.tool.pluggable.compat;

import android.app.Instrumentation;
import android.os.Handler;
import android.os.Looper;

import java.lang.reflect.InvocationTargetException;

import gsw.tool.pluggable.utils.reflect.MethodUtils;


/**
 * Activity的相关工具类
 */
public class CompatActivityThread {

    //系统的ActivityThread对象
    private static Object sActivityThread;

    private static Class sClass = null;

    /**
     * 获取系统的ActivityThread的class对象
     *
     * @return 系统的ActivityThread的class对象
     */
    public static final Class activityThreadClass() throws ClassNotFoundException {
        if (sClass == null) {
            sClass = Class.forName("android.app.ActivityThread");
        }
        return sClass;
    }

    /**
     * 通过反射，获取系统的ActivityThread对象。
     * 为了确保成功获取，第二次使用锁机制获取
     *
     * @return 系统的ActivityThread对象
     */
    public synchronized static final Object currentActivityThread() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        if (sActivityThread == null) {
            sActivityThread = MethodUtils.invokeStaticMethod(activityThreadClass(), "currentActivityThread");
            if (sActivityThread == null) {
                sActivityThread = getActivityThread();
            }
        }
        return sActivityThread;
    }

    /**
     * 通过反射，获取系统的ActivityThread对象
     * 使用对象锁机制，等到成功获取系统的ActivityThread对象，才返回结果。
     *
     * @return 系统的ActivityThread对象
     */
    private static Object getActivityThread() {
        Handler handler = new Handler(Looper.getMainLooper());
        final Object sLock = new Object();
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    sActivityThread = MethodUtils.invokeStaticMethod(activityThreadClass(), "currentActivityThread");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    synchronized (sLock) {
                        sLock.notify();
                    }
                }

            }
        });
        if (sActivityThread == null && Looper.getMainLooper() != Looper.myLooper()) {
            synchronized (sLock) {
                try {
                    sLock.wait(300);
                } catch (InterruptedException e) {
                }
            }
        }
        return null;
    }

    /**
     * 获取系统的ActivityThread的Instrumentation，用来监听Acitivity的生命周期
     *
     * @return 系统的ActivityThread的Instrumentation
     */
    public static Instrumentation getInstrumentation() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, ClassNotFoundException {
        Object obj = currentActivityThread();
        return (Instrumentation) MethodUtils.invokeMethod(obj, "getInstrumentation");
    }
}
